<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:信息中心
// +----------------------------------------------------------------------



namespace app\admin\controller;

use app\admin\model\Info as cmodel;
use think\facade\Cache;
use support\Request;
use support\Util\InitTree;
use think\facade\Db;
use app\BackendController;

class InfoController extends BackendController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {

        $cat_options = $this->getCats([]);

        return view('info/index', compact('cat_options'));
    }

    /**
     * 文章列表json数据
     * @param  Request $request [请求变量]
     * @return [type]           [json数据]
     */
    public function listData(Request $request)
    {
        $limit = $request->get('limit', 10);
        $w     = [];

        if ($request->get('title')) {
            $w[] = ['b.title', 'like', '%' . $request->get('title') . '%'];

        }
        if ($request->get('brief')) {
            $w[] = ['b.brief', 'like', '%' . $request->get('brief') . '%'];

        }
        if ($request->get('seo')) {
            $w[] = ['b.seo->meta_title|b.seo->meta_keyword|b.seo->meta_description', 'like', '%' . $request->get('seo') . '%'];

        }

        $q = cmodel::alias('a')->join("info_description b", "a.info_id=b.info_id and b.language_id=" . $this->lang_id, 'left')->field("a.*,b.title,b.content,b.brief,b.seo")->where($w);

        if ($request->get('cat_id')) {
            $q->join("info_cat c", "c.info_id=a.info_id")->where('c.cat_id', $request->get("cat_id"));
        }
        $q->order("info_id", "desc");

        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);
        foreach ($ls as $k => $v) {
            $cat_name = [];
            array_walk($v->cats->toArray(), function ($v) use (&$cat_name) {
                $v['language_id'] == $this->lang_id ? $cat_name[] = $v['cat_name'] : null;
            });
            $v->catname2 = implode(',', $cat_name);
        }

        return json(['code' => $ls->total() > 0 ? 0 : 201, 'msg' => '无数据', 'count' => $ls->total(), 'data' => $ls->items()]);
    }

    /**
     * 文章发布页面
     *
     * @return \think\Response
     */
    public function create()
    {
        $cat_options = $this->getCats([]);
        $langs       = getLangs();
        return view('info/create', compact('cat_options', 'langs'));
    }

    /**
     * 文章发布保存处理
     *
     * @param  \think\Request  $request [请求变量]
     * @return \think\Response [返回信息]
     */
    public function save(Request $request)
    {
        $post  = $request->post();
        $valid = new \app\admin\validate\Info;
        $r     = $valid->check($post);
        if (!$r) {
            $msg = ['status' => -1, 'msg' => $valid->getError()];
        } else {
            $cmodel = new cmodel();
            $cmodel->save($post);
            $info_id = $cmodel->info_id;
            //多语言处理
            array_walk($post['description'], function (&$v, $k) use ($info_id) {
                $v['info_id']     = $info_id;
                $v['language_id'] = $k;

            });
            $cmodel->description()->saveAll($post['description']);

            //分类处理

            $ins = [];
            if ($post['cat_id']) {
                foreach ($post['cat_id'] as $v) {
                    $ins[] = ['info_id' => $info_id, 'cat_id' => $v];
                }
                $cmodel->infoCats()->saveAll($ins);
            }
            $msg = ['status' => 1, 'msg' => '保存成功'];
        }
        return json($msg);
    }

    /**
     * 文章编辑页面.
     *
     * @param  int  $id [文章id]
     * @return \think\Response
     */
    public function edit(Request $request)
    {
        $id = $request->get("id");
        $data = cmodel::with("description")->find($id);
        $sel  = $data->info_cats->column('cat_id');

        $cat_options = $this->getCats($sel);
        $langs       = getLangs();

        $description = array_column($data['description']->toArray(), null, 'language_id');

        return view('info/edit', compact('data', 'cat_options', 'langs', 'description'));
    }

    /**
     * 生成分类select列表
     * @param  [type] $sel [选中项]
     * @return [type]      [数组]
     */
    private function getCats($sel)
    {

        $menus = Db::name('cat')->alias('a')->join("cat_description b", 'a.cat_id=b.cat_id and b.language_id=' . $this->lang_id, 'left')->where('a.group', '文章')->column("a.cat_id as id,b.cat_name as name,a.pid as parentid,a.sorted as `order`", "a.cat_id");
        $tree  = new InitTree;
        $tree->set_tree($menus);

        $cat_options = $tree->get_tree_multi(0, "<option value=\$id \$selected>\$spacer\$name</option>", $sel);
        $cat_options = "<option value=''>请选择</option>" . $cat_options;
        return $cat_options;

    }
    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request [表单参数]
     * @param  int  $id [文章ID]
     * @return \think\Response [返回信息]
     */
    public function update(Request $request)
    {
        $id = $request->get("id");
        $post = $request->post();        

        $valid = new \app\admin\validate\Info;
        $r     = $valid->check($post);

        $cmodel = new cmodel;
        $info   = $cmodel->where('info_id', $id)->find();
        if (!$r) {
            $msg = ['status' => -1, 'msg' => $valid->getError()];
        } else {

            //多语言处理
            $info->description()->where("info_id", $id)->delete();
            array_walk($post['description'], function (&$v, $k) use ($id) {
                $v['info_id']     = $id;
                $v['language_id'] = $k;

            });

            $info->description()->saveAll($post['description']);

            //分类关系处理
            $info->infoCats()->where("info_id", $id)->delete();
            if ($post['cat_id']) {
                $ins = [];
                foreach ($post['cat_id'] as $v) {
                    $ins[] = ['info_id' => $id, 'cat_id' => $v];
                }

                $info->infoCats()->saveAll($ins);
            }

            $info->save($post);

            $msg = ['status' => 1, 'msg' => '保存成功'];
        }
        return json($msg);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id [文章ID]
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        $id = $request->get("id");
        $ids = is_string($id) ? explode(",", $id) : $id;
        foreach ((array) $ids as $id) {
            $info = cmodel::with(['infoCats', 'description'])->find($id);
            $info->together(['infoCats', 'description'])->delete();
            unset($info);
        }
        return json(['msg' => '删除成功', 'status' => 1]);
    }
}
